<template>
    <view class="video-page">
        <!-- 显示标题 -->
        <view class="title">{{ title }}</view>
        <!-- 视频播放器 -->
        <video 
            id="videoPlayer"
            ref="videoRef" 
            :src="videoUrl" 
            controls 
            autoplay
            @loadstart="getVideo"
            @timeupdate="onTimeUpdate"
        ></video>
        
        <!-- 倍速控制 -->
        <view class="speed-controls">
            <text class="speed-label">播放速度：</text>
            <view class="speed-buttons">
                <button class="speed-btn" :class="{ 'active': playSpeed === 0.5 }" @click="setSpeed(0.5)">0.5x</button>
                <button class="speed-btn" :class="{ 'active': playSpeed === 1 }" @click="setSpeed(1)">1.0x</button>
                <button class="speed-btn" :class="{ 'active': playSpeed === 1.5 }" @click="setSpeed(1.5)">1.5x</button>
                <button class="speed-btn" :class="{ 'active': playSpeed === 2 }" @click="setSpeed(2)">2.0x</button>
            </view>
        </view>
        
        <!-- 上传/下载视频按钮 -->
        <view class="button-group">
            <button class="upload-btn" @click="chooseVideo">上传视频</button>
            <button class="download-btn" @click="downloadVideo">下载视频</button>
        </view>
        
        <!-- 视频信息显示 -->
        <view class="video-info" v-if="videoDuration > 0">
            <text>视频时长: {{ formatTime(videoDuration) }}</text>
            <text>当前进度: {{ formatTime(currentTime) }} / {{ formatTime(videoDuration) }}</text>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            courseId: '',
            sessionNumber: '',
            title: '',
            videoUrl: '',
            playSpeed: 1.0, // 默认播放速度
            currentTime: 0, // 当前播放时间
            videoDuration: 0, // 视频总时长
            isLoading: false // 加载状态
        };
    },
    onLoad(options) {
        this.courseId = options.classId;
        this.sessionNumber = options.sessionNumber;
        this.title = options.title;
        this.getVideo();
    },
    methods: {
        // 获取视频信息
        getVideo() {
            this.isLoading = true;
            uni.request({
                url: 'http://localhost:9090/user/getVideo',
                method: 'POST',
                data: {
                    courseId: this.courseId,
                    sessionNumber: this.sessionNumber
                },
                success: (res) => {
                    this.videoUrl = res.data.data.videoUrl;
                    // 设置初始播放速度
                    this.setSpeed(this.playSpeed);
                },
                fail: (err) => {
                    console.error('请求失败', err);
                    uni.showToast({
                        title: '获取视频失败',
                        icon: 'none'
                    });
                },
                complete: () => {
                    this.isLoading = false;
                }
            });
        },
        
        // 上传视频
        setVideo(url) {
            uni.request({
                url: 'http://localhost:9090/user/setVideo',
                method: 'POST',
                data: {
                    courseId: this.courseId,
                    sessionNumber: this.sessionNumber,
                    videoUrl: url
                },
                success: (res) => {
                    this.getVideo();
                    uni.showToast({
                        title: '视频设置成功',
                        icon: 'success'
                    });
                },
                fail: (err) => {
                    console.error('请求失败', err);
                    uni.showToast({
                        title: '上传失败',
                        icon: 'none'
                    });
                }
            });
        },
        
        // 选择并上传视频
        chooseVideo() {
            uni.chooseVideo({
                sourceType: ['album', 'camera'],
                maxDuration: 60,
                camera: 'back',
                success: (res) => {
                    const maxSize = 50 * 1024 * 1024; // 50M 换算为字节
                    if (res.size > maxSize) {
                        uni.showToast({
                            title: '视频大小不能超过 50M',
                            icon: 'none'
                        });
                        return;
                    }
                    const tempFilePath = res.tempFilePath;
                    
                    // 显示加载提示
                    uni.showLoading({
                        title: '上传中...',
                        mask: true
                    });
                    
                    uni.uploadFile({
                        url: 'http://localhost:9090/file/upload',
                        filePath: tempFilePath,
                        name: 'file',
                        success: (uploadRes) => {
                            // 隐藏加载提示
                            uni.hideLoading();
                            if (uploadRes.statusCode === 200) {
                                this.videoUrl = uploadRes.data;
                                this.setVideo(uploadRes.data);
                                console.log('视频上传成功，返回数据:', uploadRes.data);
                                // 弹出上传成功提示框
                                uni.showToast({
                                    title: '上传成功',
                                    icon: 'success'
                                });
                            } else {
                                console.error('上传失败，状态码:', uploadRes.statusCode);
                                // 弹出上传失败提示框
                                uni.showToast({
                                    title: '上传失败',
                                    icon: 'none'
                                });
                            }
                        },
                        fail: (err) => {
                            // 隐藏加载提示
                            uni.hideLoading();
                            console.error('上传出错:', err);
                            // 弹出上传出错提示框
                            uni.showToast({
                                title: '上传出错',
                                icon: 'none'
                            });
                        }
                    });
                },
                fail: (err) => {
                    console.error('选择视频失败:', err);
                }
            });
        },
        
        // 下载视频
        downloadVideo() {
            // 检查视频URL是否为空
            if (!this.videoUrl) {
                uni.showModal({
                    title: '提示',
                    content: '请先上传视频',
                    showCancel: false
                });
                return;
            }
            
            // 显示下载提示
            uni.showLoading({
                title: '下载中...',
                mask: true
            });
            
            // 下载视频
            uni.downloadFile({
                url: this.videoUrl,
                success: (res) => {
                    if (res.statusCode === 200) {
                        // 下载成功，保存视频到本地
                        uni.saveVideoToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '下载成功',
                                    icon: 'success'
                                });
                            },
                            fail: (err) => {
                                uni.hideLoading();
                                console.error('保存视频失败:', err);
                                if (err.errMsg.includes('auth deny')) {
                                    uni.showModal({
                                        title: '提示',
                                        content: '需要相册权限才能保存视频，请在设置中授权',
                                        success: (modalRes) => {
                                            if (modalRes.confirm) {
                                                uni.openSetting();
                                            }
                                        }
                                    });
                                } else {
                                    uni.showToast({
                                        title: '保存失败',
                                        icon: 'none'
                                    });
                                }
                            }
                        });
                    } else {
                        uni.hideLoading();
                        console.error('下载失败，状态码:', res.statusCode);
                        uni.showToast({
                            title: '下载失败',
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
                    console.error('下载出错:', err);
                    uni.showToast({
                        title: '下载出错',
                        icon: 'none'
                    });
                }
            });
        },
        
        // 设置播放速度
        setSpeed(speed) {
            this.playSpeed = speed;
            const videoContext = uni.createVideoContext('videoPlayer', this);
            videoContext.playbackRate(speed);
            console.log(`设置播放速度为: ${speed}x`);
            
            // 显示速度提示
            uni.showToast({
                title: `${speed}x 速度`,
                icon: 'none',
                duration: 1000
            });
        },
        
        // 监听播放进度
        onTimeUpdate(e) {
            this.currentTime = e.detail.currentTime;
            if (e.detail.duration) {
                this.videoDuration = e.detail.duration;
            }
        },
        
        // 格式化时间
        formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }
    }
};
</script>

<style scoped>
.video-page {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: 100vh;
    background-color: #f4f4f9;
    padding: 20px;
}

.title {
    width: 100%;
    background-color: #007bff;
    color: white;
    text-align: center;
    padding: 16px;
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

video {
    width: 90%;
    max-width: 800px;
    margin: 20px 0;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    background-color: #000;
}

.speed-controls {
    display: flex;
    align-items: center;
    margin-bottom: 15px; /* 减小底部间距 */
    width: 90%;
    max-width: 800px;
}

.speed-label {
    margin-right: 8px; /* 减小标签间距 */
    font-size: 14px; /* 减小字体大小 */
    color: #333;
}

.speed-buttons {
    display: flex;
    gap: 6px; /* 减小按钮间距 */
}

.speed-btn {
    padding: 6px 10px; /* 减小按钮内边距 */
    border: 1px solid #ccc;
    border-radius: 4px;
    background-color: #fff;
    cursor: pointer;
    font-size: 12px; /* 减小按钮字体大小 */
    transition: all 0.3s ease;
    min-width: 40px; /* 设置最小宽度 */
}

.speed-btn.active {
    background-color: #007bff;
    color: white;
    border-color: #007bff;
    transform: scale(1.05);
}

.button-group {
    display: flex;
    flex-direction: row;
    justify-content: center;
    gap: 15px;
    margin-top: 15px;
    width: 90%;
    max-width: 800px;
}

.upload-btn {
    background-color: #dc3545; /* 红色上传按钮 */
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    flex: 1;
    max-width: 200px;
}

.upload-btn:hover {
    background-color: #c82333;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.download-btn {
    background-color: #007bff; /* 蓝色下载按钮 */
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    flex: 1;
    max-width: 200px;
}

.download-btn:hover {
    background-color: #0069d9;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.video-info {
    display: flex;
    justify-content: space-between;
    width: 90%;
    max-width: 800px;
    margin-top: 10px;
    color: #666;
    font-size: 14px;
}
</style>